package com.socket.socket;

import cn.hutool.json.JSONUtil;

import java.io.*;
import java.net.*;

/**
 * 测试接收发消息
 */
public class Client {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("localhost", 7888); // 连接服务端
        System.out.println("Connected to server");

        // 启动新线程接收消息
        new Thread(() -> {
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
                String message;
                System.out.println(1111);
                while ((message = reader.readLine()) != null) {
                    System.out.println("B端接收A端发送的消息Received from server: " + message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();

        // 主线程负责发送消息
        try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()))) {
            BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
            String msgToSend;
            while (true) {
                System.out.print("B端向A端发送消息Enter message to send: ");
//                msgToSend = console.readLine();\
                String jsonString = "{\n" +
                        "          \"services\": [\n" +
                        "            {\n" +
                        "              \"service_id\": \"spaceport\",\n" +
                        "              \"properties\": {\n" +
                        "                \"light\": \"299.17Lux\",\n" +
                        "                \"th\": \"20.82℃\",\n" +
                        "                \"wet\": \"67.37%\",\n" +
                        "                \"led\": \"OFF\"\n" +
                        "              }\n" +
                        "            }\n" +
                        "          ]\n" +
                        "        }";
                String alarmJsonString = "{\"alarm\":[{\"service_id\":\"spaceport\",\"properties\":{\"ppm_alarm\":\"ON\"}}]}";
                String normalJsonString = "{\"services\":[{\"service_id\":\"spaceport\",\"properties\":{\"light\":\"217.50\",\"th\":\"26.07\",\"wet\":\"29.77%\",\"poison\":\"488.8\",\"motorStatus\":\"OFF\",\"lightStatus\":\"OFF\",\"autoStatus\":\"ON\"}}]}";
                // 使用 Hutool JSONUtil 处理为压缩字符串
                String compressedJson = JSONUtil.parseObj(jsonString).toString();
                msgToSend = normalJsonString;
                writer.write(msgToSend);
                writer.newLine();
                writer.flush();
                Thread.sleep(10000);
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
